package com.it.emall.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.it.emall.utils.JwtHelper;
import com.it.emall.utils.ResponseUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    public static final String TOKEN_KEY = "Mall-Token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //不拦截浏览器发送的检测接收是否允许跨域的请求(OPTIONS)
        if("OPTIONS".equals(request.getMethod())){
            return true;
        }
        //判断token是否有效
        String token = request.getHeader(TOKEN_KEY);
        if(new JwtHelper().verifyTokenAndGetUserId(token) != 0){//有效
            System.out.println("放行");
            return true;//放行
        }else{//无效
            Object result = ResponseUtils.fail(ResponseUtils.INVALID_TOKEN, "请先登录");
            String resultJson = new ObjectMapper().writeValueAsString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(resultJson);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
